package com.apobates.forum.graph.editor;

import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;

/**
 * apache commons fileupload实现
 *
 * @author xiaofanku
 * @since 20200528
 */
public class ApacheFileUploadConnector extends AbstractUploadConnector {
    private final static Logger logger = LoggerFactory.getLogger(ApacheFileUploadConnector.class);
    
    public ApacheFileUploadConnector(UploadHandler handler) {
        super(handler);
    }
    
    protected String execute(FileItem fileItem, File uploadDir, Optional<String> callFuntion) throws IOException {
        String redata = "-1";
        //是不是HTML常规输入项
        boolean isFormField = fileItem.isFormField();
        String fileExtensionName=FilenameUtils.getExtension(fileItem.getName());
        if(!StringUtils.isNotBlank(fileExtensionName)){
            getHandler().forceException(new IOException("获取文件的扩展名失败"));
        }
        fileExtensionName = ".".concat(fileExtensionName.toLowerCase());
        String saveFileName = (getHandler().generateFileName(fileExtensionName).isPresent()) ? getHandler().generateFileName(fileExtensionName).get() : fileItem.getName();
        if (!isFormField) {
            super.checkFileExtension(fileItem.getName());
            super.checkFileByteSize(fileItem.getSize());
            //开始保存文件
            File uploadedFile = new File(uploadDir, saveFileName);
            try {
                fileItem.write(uploadedFile);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("apache commons fileupload save file fail", e);
                }
                getHandler().forceException(new IOException(e.getMessage()));
            }
            String descrip = "" + NEWLINE;
            descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
            descrip += "/* FIELD NAME:" + fileItem.getFieldName() + NEWLINE;
            descrip += "/* Name:" + fileItem.getName() + NEWLINE;
            descrip += "/* CONTENT TYPE:" + fileItem.getContentType() + NEWLINE;
            descrip += "/* SIZE:" + fileItem.getSize() + " (Bytes)" + NEWLINE;
            descrip += "/* Directory:" + uploadedFile.getAbsolutePath() + NEWLINE;
            descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
            if (logger.isDebugEnabled()) {
                logger.debug(descrip);
            }
            //path
            redata = getHandler().getResponse(saveFileName, callFuntion);
        }
        getHandler().otherProcess(uploadDir, saveFileName, callFuntion);
        return redata;
    }
}